package com.wjk.blogs.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/*拦截器*/
@ControllerAdvice//拦截带有controller注解的方法
@Configuration
public class ControllerExceptionHandler {

    private final Logger logger= LoggerFactory.getLogger(this.getClass());//获取日志

    @ExceptionHandler(Exception.class)//加上该注解才可以拦截Exception级别的错误信息
    public ModelAndView exceptionHander(HttpServletRequest request,Exception e) throws Exception {//

        logger.error("Request URL : {} ,Exception : {}",request.getRequestURL(),e);//记录报错信息

        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){//如果是
            throw e;
        }

        ModelAndView mv=new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);//将错误信息返回到控制器中
        //返回页面
        mv.setViewName("error/error");
        return mv;
    }
}
